package ru.st.selenium.pages;

import static org.openqa.selenium.support.ui.ExpectedConditions.alertIsPresent;
import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

import ru.st.selenium.model.Film;

public class MoviePage extends InternalPage{

	public MoviePage(PageManager pages) {
		super(pages);
	}

	@FindBy(name = "name")
	private WebElement movieTitle;
	
	@FindBy(name = "year")
	private WebElement movieYear;
	
	@FindBy(name = "submit")
	private WebElement saveMovieButton;
	
	@FindBy(css = "img[alt=\"Remove\"]")
	private WebElement removeMovieButton;
	
	public MoviePage ensurePageLoaded() {
		super.ensurePageLoaded();
		wait.until(presenceOfElementLocated(By.cssSelector("footer")));
		return this;
	}
	
	public MoviePage setMovieTitle(String text) {
		movieTitle.sendKeys(Keys.chord(Keys.CONTROL, "a"), text);
		return this;
	}

	public MoviePage setMovieYear(String text) {
		movieYear.sendKeys(text);
		return this;
	}
	
	public MoviePage saveMovie() {
		saveMovieButton.click();
		return this;
	}
	
	public boolean requiredFieldErrorMessagePresent(String field) {
		WebElement titleError = driver.findElement(By.xpath("//form[@id='updateform']//td[text()='" + field + "']/../td[2]/label[@class='error']"));
		return titleError.isDisplayed();
	}
	
	public InternalPage removeMovie() {
		removeMovieButton.click();
		wait.until(alertIsPresent()).accept();
		pages.internalPage.ensureMainPageLoaded();
		return this;
	}
}
